/**
 * 根据模版信息拼装带默认值的结构数据
 * @param {*} meta 模版数据
 * @param {*} headerVO 表头VO全路径名
 * @param {String} bodyName 表体名称默认bosys，可自行填写
 * @param {String} bodyAreaId 表体名称默认从gridrelation取得，可自行填写
 */
export default function(meta, headerVO, bodyName, bodyAreaId, _headName){
    // 表头
    let headName = '';
    // 表头所有子区域
    let headAreas = [];
    if (_headName) {
        headName = _headName
        headAreas = [_headName]
    } else {
        headName = 'head';
        headAreas = ['head'];
        if(meta.formrelation){
            for(let name in meta.formrelation){
                headName = name;
                headAreas = [name];
                break;
            }
            meta.formrelation[headName] && meta.formrelation[headName].map((one)=>{
                headAreas.push(one);
            })
        }
    }
    
    // 表体列表
    let bodyNames = ['body'];
    if(bodyAreaId){
        bodyNames = [bodyAreaId];
    }else{
        if(meta.gridrelation){
            bodyNames = [];
            for(let name in meta.gridrelation){
                bodyNames.push(name);
            }
        }
    }
    // 取得表头默认数据
    let headValues={};
    headAreas.forEach((headOne)=>{
        (meta[headOne] || {}).items && (meta[headOne] || {}).items.forEach((valueOne)=>{
            if(valueOne.initialvalue){
                headValues[valueOne.attrcode]={
                    value: valueOne.initialvalue.value,
                    display: valueOne.initialvalue.display,
                    scale: valueOne.initialvalue.scale
                }
            }else if(headValues[valueOne.attrcode] == null){
                headValues[valueOne.attrcode]={
                    value: null,
                    display: null
                }
            }
        })
    })

    // 取得表体默认数据
    let bodyValues={};
    bodyNames.forEach((bodyOne)=>{
        bodyValues[bodyOne] = {
            "areaType": "table",
            "areacode": bodyOne,
            rows: [{values:{}}]
        };
        (meta[bodyOne] || {}).items && (meta[bodyOne] || {}).items.forEach((valueOne)=>{
            if(valueOne.initialvalue){
                bodyValues[bodyOne].rows[0].values[valueOne.attrcode]={
                    value: valueOne.initialvalue.value,
                    display: valueOne.initialvalue.display,
                    scale: valueOne.initialvalue.scale
                }
            }else{
                bodyValues[bodyOne].rows[0].values[valueOne.attrcode]={
                    value: null,
                    display: null
                }
            }
        })
    })
    
    // 创建数据对象
    let json = { 
        "head": {
            "pageid": headerVO,
            [headName]: {
                "areaType": "form",
                "areacode": headName,
                rows: [{values:headValues}]
            }
        }, 
        [bodyName || 'bodys']: bodyValues 
    };
    
    return json;
}